package com.bwie.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author lenovo
 */
@Configuration
public class GatewayConfig implements GlobalFilter , Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String ip = request.getRemoteAddress().getAddress().toString();

        String url = request.getPath().toString();

        if (url.contains("/user/login")) {
            return chain.filter(exchange);
        }
        if (url.contains("/pay/payWay/")) {
            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst("token");

        if(token == null){
            System.out.println("没有登录");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        Claims claims = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody();

        Integer userId = claims.get("id", Integer.class);

        String redisToken = stringRedisTemplate.opsForValue().get("token:" + userId);

        if(redisToken == null){
            System.out.println("redisToken 不存在");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        if(!redisToken.equals(token)){
            System.out.println("redisToken 不一致");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
